package jp.co.sharp.android.parents.kidsguard.activity.edit;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONObject;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.SettingActivity;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.DelDeviceConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.dto.NoteDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;


public class NoteEditActivity extends AppCompatActivity {

    private DealWithWaitingDlg mDealWithWaitingDlg;
    private boolean screenOperate = false;
    private ImageView mDelIv;
    private ImageView mConfirmIv;
    private EditText mTextEt;
    private NoteDto mNoteDto;
    private ImageView mClearIv;
    private App mApp;
    private int position = -1;
    private String noteText;
    public ParentBleTransfer mParentBleTransfer;
    private KidInfoEntity mKidInfoEntity;
    private int mViewProcess = 0;
    private boolean mUnReceiver = true;
    private static final String TAG = "TAG";
    /** ページジャンプ */
    private boolean mPageJumpFlag = false;
    /** システムホームプレス */
    private boolean mSystemHomeFlag = false;
    /** プログラムロック */
    private final String mSyncLock = "syncLock";
    /** 編集を再開しています... */
    private boolean mEditReopening = false;
    private static final int PAGE_EDIT_REOPEN = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note_edit);

        mApp=(App)getApplication();
        initReceiver();
        init();
        initListener();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "NoteEditActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                if (mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT) {
                    Message msg = new Message();
                    msg.what = PAGE_EDIT_REOPEN;
                    handler.sendMessage(msg);
                }
                mSystemHomeFlag = false;
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "PowerSettingActivity_onStart");
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }

    @Override
    protected void onStop() {
        Log.i(TAG, "NoteEditActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "NoteEditActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onDestroy();
    }


    private void init() {
        Log.i(TAG, "NoteEditActivity_init");
        Intent intent = getIntent();
        int type = intent.getIntExtra("type", 0);
        //削除ボタン
        mDelIv = findViewById(R.id.del);
        //確認ボタン
        mConfirmIv = findViewById(R.id.confirm);
        mConfirmIv.setEnabled(false);

        mTextEt = findViewById(R.id.edit);

        mClearIv = findViewById(R.id.clear);

        TextView mKidNameTv = findViewById(R.id.textViewKidName);
        String kidNameDescribe = mKidInfoEntity.getKidName()+"のキッズケータイ";
        mKidNameTv.setText(kidNameDescribe);

        //追加時、削除ボタンを非表示
        if(type == 0) {
            TextView mTitleTv = findViewById(R.id.tv_title);
            mTitleTv.setText("定型文作成");
            mDelIv.setVisibility(View.GONE);
            Toolbar.LayoutParams layoutParams = new Toolbar.LayoutParams(360, 56);
            layoutParams.setMargins(64,0,16,0);
            mConfirmIv.setLayoutParams(layoutParams);
            int id = -1;
            mNoteDto = new NoteDto();
            mNoteDto.setId(id);
            noteText = "";
        } else {
            position = intent.getIntExtra("position", 0);
            TextView mTitleTv = findViewById(R.id.tv_title);
            mTitleTv.setText("定型文編集");
            mNoteDto = (NoteDto)intent.getSerializableExtra("note");
            mTextEt.setText(mNoteDto.getText());
            noteText = mNoteDto.getText();
        }

    }


    private void initListener() {
        Log.i(TAG, "NoteEditActivity_initListener");

        mClearIv.setOnClickListener(v ->mTextEt.setText(""));

        mConfirmIv.setOnClickListener(v -> setKidNote(false));

        mDelIv.setOnClickListener(v -> {
            String message = "このアラームを削除しますか？";
            DelDeviceConfirmDlg mDelDeviceConfirmDlg = new DelDeviceConfirmDlg(NoteEditActivity.this, R.style.commonDlg, message);
            mDelDeviceConfirmDlg.show();
            mDelDeviceConfirmDlg.setOnOperateSetListener(() -> {
                mDelDeviceConfirmDlg.dismiss();
                setKidNote(true);
            });
        });

        mTextEt.setOnFocusChangeListener((v, hasFocus) -> mTextEt.setSelection(mTextEt.length()) );

        mTextEt.setOnEditorActionListener((v, actionId, event) -> (event.getKeyCode() == KeyEvent.KEYCODE_ENTER));

        mTextEt.addTextChangedListener(new TextWatcher() {
            // 入力前
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            // 入力中
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            // 入力後
            @Override
            public void afterTextChanged(Editable s) {
                if(!noteText.equals(s.toString())) {
                    mNoteDto.setText(s.toString());
                    mConfirmIv.setEnabled(true);
                } else {
                    mConfirmIv.setEnabled(false);
                }
            }
        });
    }

    /**
     * 初期化Receiver
     */
    private void initReceiver() {
        Log.i(TAG, "NoteEditActivity_initReceiver");
        mKidInfoEntity = mApp.findKidInfoBySelect();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        // Bluetooth
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        //kid戻りデータ
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        //isFinish
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = mApp.getmParentBleTransfer();
        mUnReceiver = false;
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "NoteEditActivity_systemReceiver");
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                        screenOperate = true;
                        sendExitToKid();
                    }
                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        if (!mPageJumpFlag) {
                            Message msg = new Message();
                            msg.what = PAGE_EDIT_REOPEN;
                            handler.sendMessage(msg);
                        }
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                        mSystemHomeFlag = true;
                        screenOperate = true;
                        sendExitToKid();
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    actionStateChanged(intent);
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };

    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "NoteEditActivity_receiver");
            try {
                String action = intent.getAction();
                if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                    receiverBluetoothWriteDataChanged(intent);
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                    receiverBluetoothListenerDataChanged(intent);
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };

    /***
     * ブルートゥースの状態変化
     * @param intent param
     */
    private void actionStateChanged(Intent intent) {
        BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
        String macAddress = bluetoothReceiverDto.getAddress();
        if (mApp.isMimamoriCheck(macAddress)) {
            mApp.addmLsIsMimamori(macAddress);
            // TODO Mimamori
            mViewProcess = Constants.SEND_KID_EXIT;
            sendExitToKid();
            // ページジャンプ
            mPageJumpFlag = true;
            Intent intent1 = new Intent();
            intent1.setAction(Constants.ACTION_IS_MIMAMORI);
            intent1.setClass(NoteEditActivity.this, HomeActivity.class);
            startActivity(intent1);
        } else {
            mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
            mApp.updateKidInfo(mKidInfoEntity);

            String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(NoteEditActivity.this, R.style.commonDlg, message);
            processWarringDlg.show();
            processWarringDlg.setOnOperateSetListener(() -> {
                processWarringDlg.dismiss();
                // ページジャンプ
                mPageJumpFlag = true;
                Intent intent1 = new Intent();
                intent1.setClass(NoteEditActivity.this, SettingActivity.class);
                startActivity(intent1);
            });
        }
    }

    /**
     * 受信機Bluetooth書き込みデータを変更
     * @param intent param
     */
    private void receiverBluetoothWriteDataChanged(Intent intent) {
        BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
        if (bluetoothReceiverDto.isFinished()) {
            switch (mViewProcess) {
                case Constants.SEND_KID_ENTER:
                    mViewProcess = Constants.SEND_KID_GET_INFO;
                    if (screenOperate) {
                        mEditReopening = false;
                        screenOperate = false;
                        handler.sendEmptyMessage(0);
                    }
                    break;
                case Constants.SEND_KID_EXIT:
                    if (mDealWithWaitingDlg != null && mDealWithWaitingDlg.isShowing()) {
                        mDealWithWaitingDlg.dismiss();
                    }
                    if (!screenOperate) {
                        mPageJumpFlag = true;
                        NoteEditActivity.this.finish();
                    } else if (!mSystemHomeFlag) {
                        // ページジャンプ
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setClass(NoteEditActivity.this, EditActivity.class);
                        startActivity(intent1);
                    }
                    break;

                case Constants.SEND_KID_GET_INFO:
                default:
                    break;
            }
        }
    }

    /**
     * リスナーデータ変更
     * @param intent param
     */
    private void receiverBluetoothListenerDataChanged(Intent intent) throws Exception{
        BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
        String retStr = bluetoothReceiverDto.getRetStr();
        JSONObject jsonObject = new JSONObject(retStr);

        if (RequestMethodConstants.METHOD_GET_OPERATING_STATE.equals(jsonObject.getString("method"))) {
            JSONObject data = jsonObject.getJSONObject("data");
            if (Constants.IS_USING_OK.equals(data.getString("state"))) {
                //send enter
                mViewProcess = Constants.SEND_KID_ENTER;
                new BusinessThread(Constants.SEND_KID_ENTER, PageSerialNumConstants.PAGE_SERIAL_NOTE, mParentBleTransfer, mKidInfoEntity).start();
            } else {
                mDealWithWaitingDlg.dismiss();
                String message = "別のスマートフォンから操作中のため、設定を変更できません。";
                ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(NoteEditActivity.this, R.style.commonDlg, message);
                processWarringDlg.show();
                processWarringDlg.setOnOperateSetListener(() -> {
                    processWarringDlg.dismiss();
                    NoteEditActivity.this.finish();
                });
            }
        } else if (RequestMethodConstants.METHOD_ON_OPERATE_INTERRUPT.equals(jsonObject.getString("method"))) {
            handler.sendEmptyMessage(0);
            String message = "キッズケータイが操作されました。編集を中断します。";
            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(NoteEditActivity.this, R.style.commonDlg, message);
            processWarringDlg.show();
            processWarringDlg.setOnOperateSetListener(() -> {
                processWarringDlg.dismiss();
                NoteEditActivity.this.finish();
            });
        }
    }


    /**
     * setKidNote
     * @param isDelete param
     */
    private void setKidNote(boolean isDelete) {

        Intent i = new Intent();
        i.putExtra("data", mNoteDto);
        i.putExtra("isDel", isDelete);
        i.putExtra("position", position);
        //发送数据
        setResult(Activity.RESULT_OK, i);
        mPageJumpFlag = true;
        finish();
    }


    /**
     * is usingを送信
     */
    public void sendIsUsingToKid() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", "getOperatingState");
            jsonObject.put("data", JSONObject.NULL);
            new BusinessThread(Constants.SEND_KID_IS_USING,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    jsonObject,
                    PageSerialNumConstants.PAGE_SERIAL_NOTE).start();
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    /**
     * enterを送信
     */
    public void sendEnterToKid() {
        try {
            new BusinessThread(Constants.SEND_KID_ENTER,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    null,
                    PageSerialNumConstants.PAGE_SERIAL_NOTE).start();
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }


    /**
     * exitを送信
     */
    public void sendExitToKid() {
        try {
            new BusinessThread(Constants.SEND_KID_EXIT,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    null,
                    PageSerialNumConstants.PAGE_SERIAL_NOTE).start();
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }

    }

    /**
     * ページリターンキー、フルスクリーンリターンジェスチャー
     */
    @Override
    public void onBackPressed() {
        backActivity(null);
    }

    /**
     * 前のページに戻る(値なし)
     */
    public void backActivity(View view) {
        if(mConfirmIv.isEnabled()) {
            String message = "編集内容は保存されていません。編集内容を破棄して前の画面に戻りますか？";
            DelDeviceConfirmDlg mDelDeviceConfirmDlg = new DelDeviceConfirmDlg(NoteEditActivity.this, R.style.commonDlg, message);
            mDelDeviceConfirmDlg.show();
            mDelDeviceConfirmDlg.setOnOperateSetListener(() -> {
                Intent intent = getIntent();
                mNoteDto.setId(0);
                intent.putExtra("data", mNoteDto);
                setResult(1000, intent);
                mPageJumpFlag = true;
                finish();
            });
        } else {
            Intent intent = getIntent();
            mNoteDto.setId(0);
            intent.putExtra("data", mNoteDto);
            setResult(1000, intent);
            mPageJumpFlag = true;
            finish();
        }

    }

    /**
     * Dialog閉じる
     */
    /**
     * Dialog閉じる
     */
    private Handler handler = new Handler(msg -> {
        if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
            mDealWithWaitingDlg.dismiss();
        } else if (msg.what == PAGE_EDIT_REOPEN) {
            if (!mEditReopening) {
                String message = "編集を再開しています...";
                mDealWithWaitingDlg = new DealWithWaitingDlg(NoteEditActivity.this, R.style.commonDlg, message, false);
                mDealWithWaitingDlg.show();
                screenOperate = true;
                mViewProcess = Constants.SEND_KID_IS_USING;
                new BusinessThread(Constants.SEND_KID_IS_USING,
                        mParentBleTransfer,
                        mKidInfoEntity,
                        null,
                        PageSerialNumConstants.PAGE_SERIAL_NUM_POWER_SETTING).start();
                // ブロードキャストの再登録
                unregisterReceiver(systemReceiver);
                initReceiver();
                mEditReopening = true;
            }
        }
        return false;
    });
}
